package main

import (
	"bufio"
	"encoding/csv"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)
//scp /data/project/go/imei/imei_api  root@106.13.192.223:/www/imei/
//scp /data/project/go/imei/Triad.csv  root@106.13.192.223:/www/imei/
func main() {
	//1.注册一个处理器函数
	http.HandleFunc("/get_DeviceSecret", imei)
	//2.设置监听的TCP地址并启动服务
	//参数1:TCP地址(IP+Port)
	//参数2:handler handler参数一般会设为nil，此时会使用DefaultServeMux。
	fmt.Println("-----IMEI 获取 DeviceSecret 服务已启动----")
	err := http.ListenAndServe("127.0.0.1:8080", nil)
	if err != nil {
		fmt.Printf("http.ListenAndServe()函数执行错误,错误为:%v\n", err)
		return
	}
	//860222044377289
}

type resp struct {
	Code int    `json:"code"`
	Data string `json:"data"`
}

//say hello to the world
func imei(w http.ResponseWriter, r *http.Request) {
	var res = &resp{}
	reqData, ok := r.URL.Query()["IMEI"]
	if !ok {
		res.Code = 101
		res.Data = "参数不正确"
		v, _ := json.Marshal(res)
		// 向客户端写数据
		_, _ = w.Write(v)
		return
	}
	m ,errMsg := getDesc(reqData[0])
	if errMsg != ""{
		res.Code = 101
		res.Data = errMsg
		v, _ := json.Marshal(res)
		// 向客户端写数据
		_, _ = w.Write(v)
		return
	}
	res.Data = m
	v, _ := json.Marshal(res)
	// 向客户端写数据
	_, _ = w.Write(v)
}

func getDesc(id string) (string, string) {
	fi, err := os.Open("./Triad.csv")
	if err != nil {
		return "", err.Error()
	}
	defer fi.Close()
	reader := csv.NewReader(bufio.NewReader(fi))
	if reader == nil {
		return "", "reader nil"
	}
	for {
		line, err := reader.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			return "", err.Error()
		}
		for _, s := range line {
			if id == s{
				return line[1],""
			}
		}
	}
	return "", "not fund  DeviceSecret by "+id
}
